//
//  ByBaseVC.m
//  Private_Object
//
//  Created by pro on 16/9/18.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ByBaseVC.h"

@interface ByBaseVC ()<LGTokenListenerDelegate>

@property (nonatomic, strong) NSArray *         leftItemviews;      // 左侧控件
@property (nonatomic, strong) NSArray *         rightItemviews;     // 右侧控件

@end

@implementation ByBaseVC

/** 视图已经加载 */
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupAnimatorAndGesture];
    self.view.backgroundColor = [UIColor whiteColor];   // 设置默认背景颜色
    self.tintColor = [UIColor blackColor];              // 设置默认字体颜色
    
    LGTokenListener *listen = [LGTokenListener shareTokenListener];
    listen.delegate = self;
    [listen start];
}

#pragma mark - LGTokenListenerDelegate
//监听登录状态
- (void)tokenDidInvalid {
    Authentication *auth = [[Authentication alloc] init];
    NSLog(@"%@",self);
    [auth loginWithAlertViewWithCurrentController:self titleName:@"智能备考学习" success:^{
        NSLog(@"登录成功");
    } popResult:^{
        // 退出项目。
        UIWindow *window =  [UIApplication sharedApplication].keyWindow;
        [UIView animateWithDuration:0.5f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
    }];
}

/** 视图将要出现，在该方法中设置导航栏的变动属性，本基类中定义默认属性，子类中要改变导航栏属性则需要覆写该方法 */
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    // 设置导航栏的默认属性(默认为不透明、黑色状态栏)
    [self setNaviAttributeWithTranslucent:NO stateBarLightContent:NO];
}
/** 视图已经出现 */
- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
}
/** 视图将要消失 */
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}
/** 视图已经消失 */
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
}

#pragma mark - 转场动画 和 手势 设置，这里可以设置多种动画，使用时作不同的调用即可
- (void)setupAnimatorAndGesture {
    
    __weak typeof(self) weakself = self;
    _backCongfig = ^ {
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };
    
    // 基本的转场push动画
    _normalPushAnimator = [[ByNormalPushAnimator alloc] init];
    _normalPushAnimator.toDuration = _normalPushAnimator.backDuration = 0.4;
    
    // 侧滑
    _sideslipAnimator = [[BySideslipAnimator alloc] init];
    _sideslipAnimator.toDuration = 0.3;
    _sideslipAnimator.backDuration = 0.15;
    _sideslipAnimator.backConfig = _backCongfig;        // 设置返回回调
    
    // 仿淘宝详情规格选择
    _bottomPopAnimator = [[ByBottomPopAnimator alloc] init];
    _bottomPopAnimator.backConfig = _backCongfig;       // 设置返回回调
}

#pragma mark - 自定义基类方法
/** 快捷设置导航栏属性
 translucent: YES->半透明 NO->非半透明
 light:       YES->主题色 NO->黑色
 */
#define KImageNaviBg 1
#define KImageNaviBgName @"content_nav"
#define KWholeColorNaviBgColor UIColor.whiteColor
- (void)setNaviAttributeWithTranslucent:(BOOL)translucent
                   stateBarLightContent:(BOOL)light {
    
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = light ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
    // 设置导航栏透明度
    self.navigationController.navigationBar.translucent = translucent;
    
    // 去掉导航栏背景色，用背景图代替
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    // 去掉导航栏下部的横线
    self.navigationController.navigationBar.shadowImage = translucent ? [UIImage imageWithColor:[UIColor clearColor]] : [UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:0.5]];
    // 导航栏背景图
    UIImage *bgImage = nil;
    if (translucent) {
        bgImage = [UIImage imageWithColor:[UIColor clearColor]];
    } else {
        if (KImageNaviBg) {
            bgImage = [UIImage imageNamed:KImageNaviBgName];
        } else {
            bgImage = [UIImage imageWithColor:KWholeColorNaviBgColor];
        }
    }
    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}


#pragma mark ********** items **********
#define kLeftItemTagBase  1000
#define kRightItemTagBase 2000
#define kItemMargin       10
// 创建导航栏返回按钮
- (void)addLeftBackBarButtonItem {
    
    [self addBYItemviews:@[@"back"] mode:ByNavigationItemModeText position:ByNavigationItemPositionModeLeft];
}
// 添加自定义的控件 到左右两侧
- (void)addCustomItemviews:(NSArray *)views
                  position:(ByNavigationItemPositionMode)position {
    
    // 左侧
    if (position == ByNavigationItemPositionModeLeft) {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *leftView in views) {
            NSInteger index = [views indexOfObject:leftView];
            leftView.tag = kLeftItemTagBase + index;    // 设置tag
            
            UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
            [temp addObject:leftItem];
            
        }
        self.leftItemviews = [temp copy];
        self.navigationItem.leftBarButtonItems = self.leftItemviews;
        
    }
    // 右侧
    else {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *rightView in views) {
            NSInteger index = [views indexOfObject:rightView];
            rightView.tag = kRightItemTagBase + index;    // 设置tag

            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
            [temp addObject:rightItem];
        }
        self.rightItemviews = [temp copy];
        self.navigationItem.rightBarButtonItems = self.rightItemviews;
    }
}
// 添加指定类型的 左右控件，根据mode来做不同的实现
- (void)addBYItemviews:(NSArray *)itemStrs
                  mode:(ByNavigationItemMode)mode
              position:(ByNavigationItemPositionMode)position {
    
    NSArray *views = [self createBYItems:itemStrs mode:mode position:position];
    [self addCustomItemviews:views position:position];
}
// 创建左右控件元素
- (NSArray *)createBYItems:(NSArray *)itemStrs
                      mode:(ByNavigationItemMode)mode
                  position:(ByNavigationItemPositionMode)position {

    NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:itemStrs.count];
    switch (mode) {
        case ByNavigationItemModeImage: {
            CGFloat width = 40;
            CGFloat height = 44;
            for (NSString *imageStr in itemStrs) {
                UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                imageBtn.frame = CGRectMake(0, 0, width, height);
                [imageBtn setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
                [imageBtn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:imageBtn];
//                UIEdgeInsets edge = position == ByNavigationItemPositionModeLeft ? UIEdgeInsetsMake(12, 5, 12, 15) : UIEdgeInsetsMake(12, 15, 12, 5);
//                [imageBtn setImageEdgeInsets:edge];

            }
        }
            break;
        case ByNavigationItemModeText: {
            CGFloat height = 44;
            for (NSString *textStr in itemStrs) {
                CGFloat width = [textStr getSizeOfString:16].width + 20;
                UIButton *textBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                textBtn.frame = CGRectMake(0, 0, width, height);
                [textBtn setTitle:textStr forState:UIControlStateNormal];
                [textBtn setTitleColor:self.tintColor forState:UIControlStateNormal];
                textBtn.titleLabel.font = FONT(16);
                [textBtn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:textBtn];
//                UIEdgeInsets edge = position == ByNavigationItemPositionModeLeft ? UIEdgeInsetsMake(0, 0, 0, 20) : UIEdgeInsetsMake(0, 20, 0, 0);
//                [textBtn setTitleEdgeInsets:edge];
            }
        }
            break;
        case ByNavigationItemModeImageAndText: {
            
            CGFloat height = 44;
            CGFloat margin = 4;
            for (NSString *textStr in itemStrs) {
                CGFloat width = [textStr getSizeOfString:12].width;
                width = width > 20 ? width : 20;
                UIControl *mixView = [[UIControl alloc] init];
                mixView.frame = CGRectMake(0, 0, width, height);
                [mixView addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                // 图片
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
                imgView.image = [UIImage imageNamed:textStr];
                // 文字
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 12)];
                label.font = FONT(12);
                label.text = textStr;
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = self.tintColor;
                
                [mixView addSubview:imgView];
                [mixView addSubview:label];
                
                // 设置位置
                CGFloat remainY = mixView.height - imgView.height - label.height - margin;
                imgView.top = remainY / 2;
                imgView.x = mixView.width / 2;
                label.top = imgView.bottom + margin;
                
                [views addObject:mixView];
            }
        }
            break;
            
        default:
            break;
    }
    
    return [views copy];
        
}

// 改变左右控件的颜色
- (void)setTintColor:(UIColor *)tintColor {
    _tintColor = tintColor;
    if (self.leftItemviews) {
        for (UIBarButtonItem *item in self.leftItemviews) {
            [self checkColorForSubviews:item.customView];
        }
    }
    if (self.rightItemviews) {
        for (UIBarButtonItem *item in self.rightItemviews) {
            [self checkColorForSubviews:item.customView];
        }
    }
}
// 检查并设置左右控件的颜色
- (void)checkColorForSubviews:(UIView *)view {
    
    if ([view isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)view;
        label.textColor = _tintColor;
    } else if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;
        [button setTitleColor:_tintColor forState:UIControlStateNormal];
    } else {
        for (UIView *subview in view.subviews) {
            [self checkColorForSubviews:subview];
        }
    }
}


#pragma mark - tap
- (void)btnTap:(UIButton *)button {
    if (button.tag >= kRightItemTagBase) {      // 点击了右侧的按钮
        [self rightItemsAction:button.tag - kRightItemTagBase];
    } else {                                    // 点击了左侧的按钮
        [self leftItemsAction:button.tag - kLeftItemTagBase];
    }
}
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)rightItemsAction:(NSInteger)rightIndex {
    NSLog(@"** right -> 具体实现在外部实现!");
}
// push
- (void)push:(UIViewController *)vc {
    UIViewController *pushVC = [[ByBaseNaviController alloc] initWithRootViewController:vc];
    [self zk_presentViewController:pushVC animator:self.normalPushAnimator backInteractive:true];
}

- (void)pop:(NSString *)preVcName {
    
    UIView *temp = [self.view snapshotViewAfterScreenUpdates:NO];
    
    UINavigationController *rootVC = (UINavigationController *)self.presentingViewController;
    
    while (rootVC.presentingViewController) {
        
        UIViewController *vc = nil;
        
        if ([rootVC isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController *)rootVC).viewControllers[0];
        }
        
        rootVC = (UINavigationController *)rootVC.presentingViewController;
        
        if ([vc isKindOfClass:NSClassFromString(preVcName)]) {
            vc.title = self.title;
            [vc.view addSubview:temp];
            break;
        }
    }
    
    [rootVC dismissViewControllerAnimated:YES completion:nil];
}


@end
